package com.beiding.jsonanalyzer.analyze.query;

import com.beiding.jsonanalyzer.analyze.func.FuncBase;
import com.beiding.jsonanalyzer.analyze.func.FuncFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * json节点比较器
 * 比较器可以嵌套
 * <p>
 * 比较器中类型不满足预期返回false
 */
public class NodeQueryBuilder implements FuncFactory<FuncBase<ComparatorResult>> {

    /**
     * 线性列表
     * <p>
     * 比较1 and 比较2 or 比较3
     */
    private List<Object> units = new ArrayList<>();

    public NodeQueryBuilder addElement(Object unit) {
        units.add(unit);
        return this;
    }

    @Override
    public BaseQuery createInstance() {

        //最外层为or层判断
        List<List<FuncBase>> orList = new ArrayList<>();
        //每个or比较单元内部是and型比较
        List<FuncBase> conditions = new ArrayList<>();

        for (Object unit : units) {
            //如果是比较器
            if (unit instanceof FuncFactory) {

                //加入比较单元
                FuncBase compareCondition = ((FuncFactory) unit).createInstance();
                conditions.add(compareCondition);
            } else
                //如果是or关键字
                if (unit == Connector.OR) {
                    if (conditions.size() > 0) {
                        //遇到了or比较单元
                        orList.add(conditions);
                        conditions = new ArrayList<>();
                    }
                } else
                    //如果是and关键字
                    if (unit == Connector.AND) {

                        //and连接词不错任何处理

                    } else {
                        throw new IllegalArgumentException("不支持的元素:" + unit);
                    }
        }
        //加入or比较单元
        if (conditions.size() > 0) {
            orList.add(conditions);
        }

        return new BaseQuery(orList);
    }
}
